package com.cartoonrabbit.config.security.pojo;

import com.cartoonrabbit.pojo.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class LoginUser implements UserDetails, Serializable {
    private static final long serialVersionUID = 1L;


    private User user;

//
    private List<String> roles;

    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(User user){
        this.user=user;
        this.roles= Arrays.asList(user.getRole());
    }



    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //        //根据角色获取权限
        List<SimpleGrantedAuthority> authorityList=new ArrayList<>();
        for (String  role: roles) {
            SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(role);
            authorityList.add(simpleGrantedAuthority);
        }
        return authorityList;
    }

    @Override
    public String getPassword() {
        return null;
    }


    @Override
    public String getUsername() {
        return user.getOpenId();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getIsEnable()==1?true:false;
    }

    public boolean isNew(){
        return user.getIsNew()==1?true:false;
    }
}
